<template>
	<view class="main">
		<view class="input">
			<text>选择人物的头像，多张时随机匹配</text>
			<button type="primary" size="mini" @click="upPic">上传头像</button>
		</view>
		<view class="input">
			<text>选择位置:经度:{{ location.lng }}--纬度:{{location.lat }}</text>
			<button type="primary" size="mini" @click="handerLocation">选择位置</button>
		</view>
		<view class="input">
			<text>增加人数</text>
			<input type="number" v-model="personCount" placeholder="输入数量" />
			<button type="primary" size="mini" @click="add">生成</button>
		</view>
		<view class="input">
			<text>会员 ID</text>
			<input type="text" v-model="userId" placeholder="会员 ID" />
			<button type="warn" size="mini" @click="del">删除</button>
		</view>
		<scroll-view scroll-y="true" class="list">
			<view>
				<text>虚拟人列表</text>
				<text>共计：{{ userList.length }}人</text>
				<text v-if="delUserId.length > 0">选中：{{ delUserId.length }}人</text>
			</view>
			<view class="userlist" :style="{ backgroundColor: item.isSelect ? '#ffcc00' : '#f0f0f0' }" v-for="(item, index) in userList" :key="index" @click="handerselect(index)">
				<view class="item">
					<image :src="item.userId[0].nicPic.url" mode=""></image>
				</view>
				<view class="item">{{ item.userId[0].userId }}</view>
				<view class="item">{{ item.userId[0].userName }}</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();
import getGridCode from '../../utils/getGridCode';
export default {
	data() {
		return {
			location:{
			lng: 0,
			lat: 0
			},
		
			personCount: 0,
			name: '',
			connectionId: '',
			userList: [],
			userTelCounter: 0, // 新增计数器
			nicPics: [],
			delUserId: [],
			userId:""
		};
	},
	watch: {
		userList: {
			handler(newVal) {
				// 过滤出 isSelect 为 true 的用户
				const selectedUsers = newVal.filter((item) => item.isSelect);
				// 提取选中用户的 userId 组成数组
				this.delUserId = selectedUsers.map((item) => item.userId);
			},
			deep: true
		},

	},
	mounted() {
		uni.$on('clickLocation', (res) => {
			this.location.lng = res.lng;
			this.location.lat = res.lat;
			console.log("this.location: " + JSON.stringify(this.location));
			
		});
	},
	beforeDestroy() {
		uni.$off('clickLocation')
	},
	onLoad() {
		 const eventChannel = this.getOpenerEventChannel();
		 if(eventChannel){
			 eventChannel.on("Locations", (res)=>{
				 this.location=res
			 })
		 }
		console.log("this.location: " + JSON.stringify(this.location));
		this.initdata();
		
	},
	methods: {
		async initdata() {
			const isSelect = false;
			try {
				const result = await db.collection('opendb-poi').where({isRandom: true}).getTemp();
				console.log(result);
				const res=await db.collection(result,'linli-user').get()
				console.log("74747474",res);
                this.userList=res.data.map(item=>({isSelect:isSelect,...item		
					
				}))
			} catch (error) {
				console.error('数据初始化失败:', error);
			}
		},

		async add() {
			if (this.personCount === 0) {
				uni.showToast({
					title: '请输入人数'
				});
				return;
			} 
			try{
				const nicdata= await db.collection('nicpic').get()
			if(nicdata.data.length===0){
					uni.showToast({
					title: '请选择头像'
				});
				return
			}
			 this.nicPics=nicdata.data  
				
				}catch(e){
				console.error(e)
			}		
			
		
			try {
				for (let i = 1; i <= this.personCount; i++) {
					const userTel = `179${Date.now().toString().slice(-8)}${this.userTelCounter}`;
					this.userTelCounter++; // 每次生成新的 userTel 后计数器加 1
					const userId=this.generateString(userTel).userId
					const location={longitude:this.randomLocation().lng,latitude:this.randomLocation().lat}
					console.log(getGridCode(location));
					const updateData = {
						receiveDistance: 1000,
						location: new db.Geo.Point(location.longitude, location.latitude),
						connectionId: `11112222${Date.now()}`,
						userId: userId,
						isRandom: true,
						title:userId,
						grid:getGridCode(location)
					};
					const user={
						userTel: userTel,
						nicName: userId,
						userId:userId,
						nicPic: this.nicPics[Math.floor(Math.random() * this.nicPics.length)],
						isRandom:true
						
					}
					this.userList.push(updateData);
					await db.collection('opendb-poi').add(updateData);
					await db.collection('linli-user').add(user)
				}
			} catch (e) {
				console.error(JSON.stringify(e));
			}
		},
		generateString(phoneNumber) {
			const lastFourDigits = phoneNumber.slice(-4);
			let randomLetters = '';
			const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			for (let i = 0; i < 4; i++) {
				const randomIndex = Math.floor(Math.random() * letters.length);
				randomLetters += letters[randomIndex];
			}
			return {
				userId: randomLetters + lastFourDigits,
				userTel: phoneNumber
			};
		},
		randomLocation() {
			const randomLonOffset = Math.random() * 0.1 - 0.05; // 生成 -0.5 到 0.5 之间的随机数
			const lng = parseFloat(this.location.lng) + randomLonOffset;
			const randomLatOffset = Math.random() * 0.1 - 0.05; // 生成 -0.5 到 0.5 之间的随机数
			const lat = parseFloat(this.location.lat) + randomLatOffset;
			return {
				lng,
				lat
			};
		},
		async upPic() {
			try {
				const chooseRes = await uni.chooseImage({
					count: 100
				});
				const tempFilePaths = chooseRes.tempFilePaths;
				const downloadUrls = [];

				for (const path of tempFilePaths) {
					console.log('断点1');
					const cloudPath = `avatars/${new Date().getTime()}-${Math.floor(Math.random() * 1000)}.jpg`;
				console.log("上传图片: " + JSON.stringify(cloudPath));
					try {
						const uploadRes = await uniCloud.uploadFile({
							cloudPath,
							filePath: path
						});
						console.log("上传图片后的: " + JSON.stringify(uploadRes));
						if (uploadRes.fileID) {
							try {
								const getUrlRes = await uniCloud.getTempFileURL({
										fileList: [uploadRes.fileID]
								});
								console.log("getUrlRes: " + JSON.stringify(getUrlRes));
								if (getUrlRes.fileList[0].tempFileURL) {
									downloadUrls.push(getUrlRes.fileList[0].tempFileURL);
									try {
										await db.collection('nicpic').add({
											url: getUrlRes.fileList[0].tempFileURL,
											fileID:uploadRes.fileID
										});
									} catch (dbError) {
										console.error('向数据库添加数据时出错:', JSON.stringify(dbError));
									}
								}
							} catch (getUrlError) {
								console.error('获取临时文件 URL 时出错:', getUrlError);
							}
						}
					} catch (uploadError) {
						 console.error('上传文件时出错:', uploadError.errMsg);
					    console.error('上传文件时出错详细信息:', JSON.stringify(uploadError));
					}
				}

				console.log('下载地址数组:', downloadUrls);
				return downloadUrls;
			} catch (error) {
				console.error('选择或上传图片时出错:', error);
			}
		},
		async del() {
			// 检查是否存在待删除的用户 ID 且数组不为空
			if (this.delUserId && this.delUserId.length > 0) {
				try {
					// 从数据库集合 'opendb - poi' 中删除 userId 等于 this.delUserId 的数据
					const delData = await db
						.collection('opendb-poi')
						.where({
							userId: db.command.in(this.delUserId),
							isRandom: true
						})
						.remove();
					uni.showModal({
						title: '删除成功',
						content: JSON.stringify(delData)
					});

					// 更新本地的 userList 数据
					this.userList = this.userList.filter((item) => !this.delUserId.includes(item.userId));

					// 清空 delUserId 数组
					this.delUserId = [];
				} catch (error) {
					let errorMessage = '未知错误';
					if (error.errMsg) {
						errorMessage = error.errMsg;
					}
					uni.showModal({
						title: '删除失败',
						content: errorMessage
					});
					console.error('删除失败', error);
				}
			}
		},
		handerLocation() {
			uni.navigateTo({
				url: '/own/map/map'
			});
		},
		handerselect(i) {
			this.userList[i].isSelect = !this.userList[i].isSelect;
		}
	}
};
</script>

<style lang="scss" scoped>
.main {
	display: flex;
	flex-direction: column;
	height: 100vh;
}
.list {
	display: flex;
	flex: 1;

	width: 100%;
	font-size: 25rpx;
}
.userlist {
	display: flex;
	padding: 20rpx;
	margin: 5rpx;
	background-color: white;
}

.item {
	display: flex;
	padding-left: 10rpx;
	image {
		width: 50rpx;
		height: 50rpx;
	}
}
.isSelect {
	background-color: #ccc;
}

.input {
	display: flex;
	align-items: center;
	flex-direction: row;
	margin: 10rpx;
	padding: 20rpx;
	background-color: #ccc;
	input {
		margin-left: 10rpx;
		background-color: white;
		border-radius: 5rpx;
		padding: 10rpx;
	}
}
</style>
